package middleware

import (
	"strings"

	"sysu-giep/internal/database/models"
	"sysu-giep/pkg/auth"
	"sysu-giep/pkg/logger"
	"sysu-giep/pkg/response"

	"github.com/gin-gonic/gin"
)

// JWTManager JWT管理器实例
var JWTManager *auth.JWTManager

// SetJWTManager 设置JWT管理器
func SetJWTManager(manager *auth.JWTManager) {
	JWTManager = manager
}

// JWTAuth JWT认证中间件
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization头
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			response.Unauthorized(c, "未提供认证令牌")
			c.Abort()
			return
		}

		// 检查Bearer前缀
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			response.Unauthorized(c, "认证令牌格式错误")
			c.Abort()
			return
		}

		// 验证令牌
		claims, err := JWTManager.ValidateToken(parts[1])
		if err != nil {
			logger.ErrorLog(err.Error())
			response.Unauthorized(c, "认证令牌无效")
			c.Abort()
			return
		}

		// 检查用户状态
		if claims.Status != models.StatusApproved {
			response.Forbidden(c, "用户状态异常")
			c.Abort()
			return
		}

		// 将用户信息存储到上下文
		c.Set("user_id", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("email", claims.Email)
		c.Set("role", claims.Role)
		c.Set("status", claims.Status)

		c.Next()
	}
}

// RequireRole 角色权限中间件
func RequireRole(roles ...models.UserRole) gin.HandlerFunc {
	return func(c *gin.Context) {
		userRole, exists := c.Get("role")
		if !exists {
			response.Unauthorized(c, "用户信息不存在")
			c.Abort()
			return
		}

		role, ok := userRole.(models.UserRole)
		if !ok {
			response.InternalServerError(c, "角色信息格式错误")
			c.Abort()
			return
		}

		// 检查角色权限
		hasRole := false
		for _, requiredRole := range roles {
			if role == requiredRole {
				hasRole = true
				break
			}
		}

		if !hasRole {
			response.Forbidden(c, "权限不足")
			c.Abort()
			return
		}

		c.Next()
	}
}

// RequireStatus 状态检查中间件
func RequireStatus(statuses ...models.UserStatus) gin.HandlerFunc {
	return func(c *gin.Context) {
		userStatus, exists := c.Get("status")
		if !exists {
			response.Unauthorized(c, "用户信息不存在")
			c.Abort()
			return
		}

		status, ok := userStatus.(models.UserStatus)
		if !ok {
			response.InternalServerError(c, "状态信息格式错误")
			c.Abort()
			return
		}

		// 检查用户状态
		hasStatus := false
		for _, requiredStatus := range statuses {
			if status == requiredStatus {
				hasStatus = true
				break
			}
		}

		if !hasStatus {
			response.Forbidden(c, "用户状态不符合要求")
			c.Abort()
			return
		}

		c.Next()
	}
}

// GetCurrentUserID 获取当前用户ID
func GetCurrentUserID(c *gin.Context) uint {
	userID, exists := c.Get("user_id")
	if !exists {
		return 0
	}
	if id, ok := userID.(uint); ok {
		return id
	}
	return 0
}

// GetCurrentUsername 获取当前用户名
func GetCurrentUsername(c *gin.Context) string {
	username, exists := c.Get("username")
	if !exists {
		return ""
	}
	if name, ok := username.(string); ok {
		return name
	}
	return ""
}

// GetCurrentRole 获取当前用户角色
func GetCurrentRole(c *gin.Context) models.UserRole {
	role, exists := c.Get("role")
	if !exists {
		return ""
	}
	if userRole, ok := role.(models.UserRole); ok {
		return userRole
	}
	return ""
}
